import Vue from 'vue'
import Vuex from 'vuex'
import {getToken, getUserInfo, setToken, setUserInfo} from "../cookie";
import {get_info, login} from "../api";
import {changeTabbar} from "@/utils";

Vue.use(Vuex)

const store = new Vuex.Store({
    state:{
        userInfo:getUserInfo() || {},
        showLogin:false,
        token: getToken() || false
    },
    mutations:{
        SET_USER_INFO(state,userInfo){
            state.userInfo = userInfo
        },
        SET_TOKEN(state,token){
            state.token = token
        },
        SET_SHOWLOGIN(state,showLogin){
            state.showLogin = showLogin
        }
    },
    getters:{
        getUserInfo: state => state.userInfo,
        getToken:state => state.token,
        getLogin:state => state.showLogin
    },
    actions:{
        login({commit},form){
            return new Promise((resolve, reject) => {
                login(form).then(e=>{
                    setToken(true)
                    commit('SET_TOKEN',true)
                    setUserInfo(e.data.data)
                    commit('SET_USER_INFO',e.data.data)
                    changeTabbar(e.data.data.isPay)
                    resolve(e.data.data)
                }).catch(err=>{
                    reject(err)
                })
            })
        },
        // 唤起首页登录
        handleChangeLogin({commit,state},login){
            console.log(login)
            login ? uni.hideTabBar() :uni.showTabBar()
            commit('SET_SHOWLOGIN',login)
        },
        // 获取用户信息
        getInfo({commit,state}){
            return new Promise((resolve, reject) => {
                get_info({
                    userId:state.userInfo.userId
                }).then(e=>{
                 /*   if( e.data.data.isPay === "2" ){
                        uni.setTabBarItem({
                            index:0,
                            text:"权益",
                            pagePath:"/pages/index/index2"
                        })
                    }*/
                    // changeTabbar(e.data.data.isPay)
                    setUserInfo(e.data.data)
                    commit('SET_USER_INFO',e.data.data)
                    resolve(e.data.data)
                }).catch(e=>{
                    reject(e.data)
                })
            })
        },
        logout({commit,state}){
            return new Promise((resolve, reject) => {

                uni.removeStorageSync('token')
                uni.removeStorageSync('userInfo')
                commit('SET_TOKEN',false)
                commit('SET_USER_INFO',{})
                resolve()
            })
        }
    }
})

export default store
